
var socket;
// 图像信息
var screenInfo;
// 图像显示url
var url;


// 屏幕宽度（像素）
var screenWidth = window.screen.width;
// 屏幕高度（像素）
var screenHeight = window.screen.height;
// 视口宽度（像素）
var viewportWidth = window.innerWidth;
// 视口高度（像素）
var viewportHeight = window.innerHeight;
// 图像缩放比
var widthZoom = 1;
var heightZoom = 1;

// 工具栏
var toolbar = document.getElementById('toolbar');
// 图像父容器
var content = document.getElementById('content');
// 右键菜单
var customMenu = document.getElementById('custom-menu');

//跟踪按键按下,keydown,keyup
const keyStates = {
    'Control': '',
    'Shift': '',
    'Alt': '',
};
//按键，鼠标信息
const ctrlInfo = {
    'license':'bcc746fffee3e368-00002ee0-00000005-0a2e47ca7e232344-64ef2a51',
    'x':0,
    'y':0,
    'widthZoom':widthZoom,
    'heightZoom':heightZoom,
    'key':'',
    'keyCode':'',
    'mouseKey':'',
    'mouseWheel':''
};


/***toolbar************************************************/
// 监听toolbar的右键contextmenu事件
toolbar.addEventListener('contextmenu', function (event) {
    event.preventDefault();
    showMenu(event.pageX, event.pageY);
}, false);

// 监听content的右键contextmenu事件并阻止默认行为
content.addEventListener('contextmenu', function (event) {
    event.preventDefault();
}, false);

// 显示右键菜单
function showMenu(x, y) {
    customMenu.style.left = x + 'px';
    customMenu.style.top = y + 'px';
    customMenu.style.display = 'block';
}
// 隐藏右键菜单
function hideMenu() {
    customMenu.style.display = 'none';
}

// 页面内左键点击时隐藏右键菜单
document.addEventListener('click', function (event) {
    if (!customMenu.contains(event.target) && !toolbar.contains(event.target)) {
        hideMenu();
    }
}, false);

/**
 * 拖动toolbar
 */
document.addEventListener('DOMContentLoaded', function () {
    const topBar = document.getElementById('toolbar');
    let offsetX, initialX;
    let isDragging = false;
    let startX, initialLeft;

    topBar.addEventListener('mousedown', function (e) {
        isDragging = true;
        startX = e.clientX;
        initialLeft = parseInt(window.getComputedStyle(topBar).left, 10) || 0;
        document.body.style.userSelect = 'none';
    });

    document.addEventListener('mousemove', function (e) {
        if (isDragging) {
            const deltaX = e.clientX - startX;
            const newLeft = initialLeft + deltaX;
            const maxLeft = window.innerWidth - topBar.offsetWidth;
            topBar.style.left = Math.max(0, Math.min(maxLeft, newLeft)) + 'px';
        }
    });

    document.addEventListener('mouseup', function () {
        isDragging = false;
        document.body.style.userSelect = '';
    });

    topBar.style.left = 'calc(50% - 50px)';
    // 监听窗口resize事件
    window.addEventListener('resize', updateDimensions);
});

// 监听窗口resize事件->调整可视图像尺寸
function updateDimensions() {
    viewportWidth = window.innerWidth;
    viewportHeight = window.innerHeight;
    if (screenInfo) {
        viewportWidth = window.innerWidth;
        viewportHeight = window.innerHeight;
        widthZoom = viewportWidth / screenInfo.width;
        heightZoom = viewportHeight / screenInfo.height;
        imgElement = document.getElementById('image-element-id');
        // 设置图像的宽度和高度（以像素为单位）
        imgElement.style.width = (screenInfo.width * widthZoom) + 'px';
        imgElement.style.height = (screenInfo.height * heightZoom) + 'px';

        ctrlInfo['widthZoom'] = widthZoom;
        ctrlInfo['heightZoom'] = heightZoom;
    }
}

updateDimensions();

/****按键******************************************/
// 监听鼠标左键按下事件
document.addEventListener('mousedown', function(event) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        // 0 表示鼠标左键
        // 1 表示鼠标中键
        // 2 表示鼠标右键
        ctrlInfo['mouseKey'] = event.button;
        const merged = Object.assign({}, ctrlInfo, keyStates);
        socket.send(JSON.stringify(merged));
        //恢复默认值
        ctrlInfo['mouseKey']=-1;
    }
});

document.addEventListener('wheel', function(event) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        // deltaY 表示垂直方向的滚动量
        // 正值表示向下滚动，负值表示向上滚动
        if (event.deltaY < 0) {
            ctrlInfo['mouseWheel'] = -1;
        } else {
            ctrlInfo['mouseWheel'] = 1;
        }
        const merged = Object.assign({}, ctrlInfo, keyStates);
        socket.send(JSON.stringify(merged));
        //恢复默认值
        trlInfo['mouseWheel']=0;
    }
});

document.addEventListener('mousemove', (event) => {
    const x = event.pageX;
    const y = event.pageY;
    ctrlInfo['x'] = x / widthZoom;
    ctrlInfo['y'] = y / heightZoom;
    if (socket && socket.readyState === WebSocket.OPEN) {
        const merged = Object.assign({}, ctrlInfo, keyStates);
        socket.send(JSON.stringify(merged));
    }
});

document.addEventListener('keydown', (event) => {
    if(keyStates[event.key]){
        keyStates[event.key] = 'keydown';
    }
    ctrlInfo['key'] = event.key;
    ctrlInfo['keyCode'] = event.keyCode;
    if (socket && socket.readyState === WebSocket.OPEN) {
        const merged = Object.assign({}, ctrlInfo, keyStates);
        socket.send(JSON.stringify(merged));
    }
    if(keyStates[event.key]){
        keyStates[event.key] = '';
    }
});

//document.addEventListener('keyup', (event) => {
//    if(keyStates[event.key]) {
//        keyStates[event.key] = 'keyup';
//    }
//    if (socket && socket.readyState === WebSocket.OPEN) {
//        const merged = Object.assign({}, ctrlInfo, keyStates);
//        socket.send(JSON.stringify(merged));
//    }
//    if(keyStates[event.key]){
//        keyStates[event.key] = '';
//    }
//});

/****websocket******************************************/
// 打开连接的函数
function openWebSocket() {
    if (!socket || socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) {
        socket = new WebSocket(websocketUrl);
        // 发送初始消息
        socket.onopen = function(event) {
            const merged = Object.assign({}, ctrlInfo, keyStates);
            socket.send(JSON.stringify(merged));
        };
        // 监听消息事件
        socket.onmessage = function(event) {
            // 处理接收到的消息
            if (event.data instanceof ArrayBuffer) {
                handleImageMessage(event.data);
            } else if (event.data instanceof Blob) {
                handleImageMessage(event.data);
            } else {
                // 处理文本消息（如果有的话）
                if (event.data) {
                    screenInfo = JSON.parse(event.data);
                    updateDimensions();
                }
            }
        };
        // 监听错误事件
        socket.onerror = function(error) {
            console.log("WebSocket error:", error);
        };
        // 监听关闭事件
        socket.onclose = function(event) {
            console.log("WebSocket connection closed.", event);
        };
    }
}

// 关闭连接的函数
function closeWebSocket() {
    if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
        socket.close();
    }
}

// 从websocket消息显示图像
function handleImageMessage(data) {
    if (url) {
        // 该释放不需要的URL占用的内存
        URL.revokeObjectURL(url);
    }
    // 创建一个Blob对象，假设图片是PNG格式（根据服务器发送的实际格式调整）
    const blob = new Blob([data], { type: 'image/jpeg' });
    // 创建一个URL，该URL指向内存中的Blob对象
    url = URL.createObjectURL(blob);
    // 使用该URL显示图片
    const imgElement = document.getElementById('image-element-id');
    imgElement.src = url;
}
